package com.example.travelservlet.plan.controller;

import com.example.travelservlet.city.service.CityService;
import com.example.travelservlet.collectionEntertainment.service.CollectionEntertainmentService;
import com.example.travelservlet.entertainment.service.EntertainmentService;
import com.example.travelservlet.entertainmentLabel.service.EntertainmentLabelService;
import com.example.travelservlet.entertainmentPlan.service.EntertainmentPlanService;
import com.example.travelservlet.entity.*;
import com.example.travelservlet.plan.service.PlanService;
import com.example.travelservlet.totalPlan.service.TotalPlanService;
import com.example.travelservlet.user.domain.Result;
import com.example.travelservlet.user.exception.BizException;
import com.example.travelservlet.user.service.UserService;
import com.example.travelservlet.userLabel.service.UserLabelService;
import com.example.travelservlet.util.MyTime;
import com.example.travelservlet.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.yaml.snakeyaml.nodes.NodeId.sequence;

/**
 * @author 30697
 */
@RestController
@RequestMapping("/PlanController")
public class PlanController {
    @Autowired
    private PlanService planService;

    @Autowired
    private TotalPlanService totalPlanService;

    @Autowired
    private UserService userService;
    @Autowired
    private CollectionEntertainmentService collectionEntertainmentService;
    @Autowired
    private EntertainmentService entertainmentService;
    @Autowired
    private EntertainmentPlanService entertainmentPlanService;
    @Autowired
    private EntertainmentLabelService entertainmentLabelService;
    @Autowired
    private CityService cityService;
    @Autowired
    private UserLabelService userLabelService;

    private List<Entertainment> pmList = new ArrayList<>();
    private List<Entertainment> amList = new ArrayList<>();

    @GetMapping("/findPlanByPlanId/{planId}")
    public Result<Plan> findPlanByPlanId(@Valid String planId){
        Plan planByPlanId = planService.findPlanByPlanId(planId);
        return ResultUtil.success(planByPlanId);
    }

    @Transactional
    @GetMapping("/create/{loginName}/{totalPlanId}/{planId}")
    public Result<Map<String,List<EntertainmentPlan>>> create(@PathVariable String loginName,@PathVariable String totalPlanId,@PathVariable String planId){
        Map<String,List<EntertainmentPlan>> stringListMap = new HashMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        User user = userService.findUserByLoginName(loginName);
        City city = cityService.findCityById(user.getCityId());
        List<UserLabel> all = userLabelService.findAll();
        List<String> userId = new ArrayList<>();
        for (UserLabel userLabel : all){
            userId.add(userLabel.getUserId());
        }

        List<String> labels = userLabelService.findLabelIdsByUserId(user.getUserId());
        List<String> entertainmentIds = entertainmentLabelService.listEntertainmentIds(labels);
        List<Entertainment> entertainments = new ArrayList<>();

        if (userId.contains(user.getUserId())){
            entertainments = entertainmentService.findEntertainmentsByCityIdAndEntertainmentIds(city, entertainmentIds, "scenery");
        }else {
            entertainments = entertainmentService.findAll(city, "scenery");
        }
        getData(entertainments);

        List<EntertainmentPlan> amEntertainmentPlanList = new ArrayList<>();
        MyTime amTime = new MyTime(8,0,0);
        MyTime pmTime = new MyTime(14,0,0);
        for (Entertainment en : amList){
            EntertainmentPlan  entertainmentPlan = new EntertainmentPlan();
            entertainmentPlan.setEntertainmentPlanId(UUID.randomUUID().toString());
            entertainmentPlan.setPlanId(planId);
            entertainmentPlan.setEntertainmentId(en.getEntertainmentId());
            entertainmentPlan.setSequence(amList.indexOf(en));
            amTime.addMinute(20);
            entertainmentPlan.setBeginTime(amTime.display());
            amTime.addMinute(en.getTime());
            entertainmentPlan.setEndTime(amTime.display());
            amEntertainmentPlanList.add(entertainmentPlan);
        }
        List<EntertainmentPlan> amEntertainmentPlans = entertainmentPlanService.createEntertainmentPlans(amEntertainmentPlanList);
        stringListMap.put("am",amEntertainmentPlans);
        List<EntertainmentPlan> pmEntertainmentPlanList = new ArrayList<>();
        for (Entertainment en : pmList){
            EntertainmentPlan  entertainmentPlan = new EntertainmentPlan();
            entertainmentPlan.setEntertainmentPlanId(UUID.randomUUID().toString());
            entertainmentPlan.setPlanId(planId);
            entertainmentPlan.setEntertainmentId(en.getEntertainmentId());
            entertainmentPlan.setSequence(amList.size()+pmList.indexOf(en));
            pmTime.addMinute(20);
            entertainmentPlan.setBeginTime(pmTime.display());
            pmTime.addMinute(en.getTime());
            entertainmentPlan.setEndTime(pmTime.display());
            pmEntertainmentPlanList.add(entertainmentPlan);
        }
        List<EntertainmentPlan> pmEntertainmentPlans = entertainmentPlanService.createEntertainmentPlans(pmEntertainmentPlanList);
        stringListMap.put("pm",pmEntertainmentPlans);
//        EntertainmentPlan save= entertainmentPlanService.createEntertainmentPlan(entertainmentPlan);
        return ResultUtil.success(stringListMap);
    }

    public void getData(List<Entertainment> entertainments){
        int count = (int) (Math.random()*10+1);

        Random random = new Random();
        int size = entertainments.size();
        Set<Entertainment> totals = new HashSet<Entertainment>();
        List<Entertainment> resultList = new ArrayList<>();
        while (totals.size()<count){
            totals.add(entertainments.get(random.nextInt(size)));
        }
        Iterator iterator = totals.iterator();
        while (iterator.hasNext()){
            Entertainment next = (Entertainment) iterator.next();
            resultList.add(next);
        }

//        int sum = 10*count;
//        for (Entertainment entertainment : resultList){
//            sum = sum + entertainment.getTime();
//        }
//        if (sum >= 240 & sum <= 270){
//            list = resultList;
//        }else {
//            getData(entertainments);
//        }

        List<Entertainment> pm = new ArrayList<>();
        List<Entertainment> am = new ArrayList<>();
        int amCount = (int) (Math.random()*count+1);
        int pmCount = count - amCount;
        int amSum = 20*amCount;
        int pmSum = 20*pmCount;
        for (int i = 0;i < amCount;i++){
            Entertainment entertainment = resultList.get(i);
            amSum = amSum + entertainment.getTime();
            am.add(entertainment);
        }
        for (int i = amCount;i < count;i++){
            Entertainment entertainment = resultList.get(i);
            pmSum = pmSum + entertainment.getTime();
            pm.add(entertainment);
        }
        if ((amSum >= 180 & amSum <= 300)&&(pmSum >= 180 & pmSum <= 300)){
            amList = am;
            pmList = pm;
        }else {
            getData(entertainments);
        }
    }


    @PostMapping("/createPlan/{loginName}")
    public Result<Plan> createPlan(@Valid String planId,@Valid String planName, @Valid String beginTime,@PathVariable String loginName){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Plan plan = new Plan();
        if (planId ==null){
            plan.setPlanId(UUID.randomUUID().toString());
        }else {
            plan.setPlanId(planId);
        }
        if (planId ==null){
            plan.setPlanId(UUID.randomUUID().toString());
        }else {
            plan.setPlanId(planId);
        }
        if (planName==null){
            plan.setPlanName("计划表");
        }else {
            plan.setPlanName(planName);
        }
        if (beginTime==null){
            plan.setBeginTime(dateFormat.format(new Date()));
        }else {
            try {
            Date begin = dateFormat.parse(beginTime);
            plan.setBeginTime(dateFormat.format(begin));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        }
        User user = userService.findUserByLoginName(loginName);
        TotalPlan totalPlan = totalPlanService.findTotalPlanByUserId(user.getUserId());
        plan.setTotalPlanId(totalPlan.getTotalPlanId());
        Plan save = planService.createPlan(plan);
        return ResultUtil.success(save);
    }

    @PostMapping("/updatePlan")
    public Result<Plan> updatePlan(@Valid String planName, @Valid String beginTime){
        Plan plan = new Plan();
        plan.setPlanName(planName);
        plan.setBeginTime(beginTime);
        Plan updatePlan = planService.updatePlan(plan);
        return ResultUtil.success(updatePlan);
    }

    @GetMapping("/findPlansByTotalPlanId/{totalPlanId}")
    public Result<List<Plan>> findPlansByTotalPlanId(@PathVariable String totalPlanId){
        List<Plan> plans = planService.findPlansByTotalPlanId(totalPlanId);
        return ResultUtil.success(plans);
    }

    @Transactional
    @GetMapping("/deletePlanById/{planId}")
    public Result deletePlanById(@PathVariable String planId){
        planService.deleteByPlanId(planId);
        return ResultUtil.success("删除成功");
    }

//    @GetMapping("/findPlanBySequence/{loginName}")
//    public Result<List<Plan>> findPlanBySequence(@PathVariable String loginName,Plan plan){
//        User user = userService.findUserByLoginName(loginName);
//        TotalPlan totalPlan = totalPlanService.findTotalPlanByUserId(user.getUserId());
//        List<Plan> plans = planService.findPlanBySequenceAndTotalPlanId(plan,totalPlan.getTotalPlanId());
//        return ResultUtil.success(plans);
//    }

//    @GetMapping("/findPlansByDate/{loginName}/{beginTime}")
//    public Result<List<Plan>> findPlansByDate(@PathVariable String loginName,@PathVariable String beginTime,Plan plan){
//        System.out.print(beginTime);
//        User user = userService.findUserByLoginName(loginName);
//        TotalPlan totalPlan = totalPlanService.findTotalPlanByUserId(user.getUserId());
//        List<Plan> planAll = planService.findPlanByBeginTimeAndAndTotalPlanId(beginTime,totalPlan.getTotalPlanId());
//        return ResultUtil.success(planAll);
//    }

    @GetMapping("/setPlanToUsing/{planId}")
    public Result<Plan> setPlanToUsing(@PathVariable String planId){
        planService.setPlanToUsing(planId);
        return ResultUtil.success("设置成功");
    }

    @GetMapping("/getPlanUnderUsing/{totalPlanId}")
    public Result<String> getPlanUnderUsing(@PathVariable String totalPlanId){
        System.out.println(totalPlanId);
        List<Plan> plans = planService.findPlansByTotalPlanId(totalPlanId);
        Plan plan = new Plan();
        plans.forEach(f ->{
            if (f.getUseIndex() == 1) {
                plan.setUseIndex(f.getUseIndex());
                plan.setPlanName(f.getPlanName());
                plan.setPlanId(f.getPlanId());
                plan.setTotalPlanId(f.getTotalPlanId());
                plan.setBeginTime(f.getBeginTime());
            }
        });
        return ResultUtil.success(plan);
//        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
//        String today = dateFormat1.format(new Date());
//        String dateStr = today+" "+format.format(plan.getBeginTime());
//        try {
//            Date newDate = dateFormat.parse(dateStr);
//            if (newDate.before(new Date())){
//                return ResultUtil.success(plan);
//            }else {
//                return ResultUtil.success(null);
//            }
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        return ResultUtil.success(null);
    }

}
